import 'dart:convert';

class BaseResponse<T> {
  String? code; // 响应代码
  String? response; // 响应结果
  String? desc; // 描述信息
  T? data; // 泛型数据
  String? message; // 错误消息

  BaseResponse({
    this.code,
    this.response,
    this.desc,
    this.data,
    this.message,
  });

  // 从 JSON 解析
  factory BaseResponse.fromJson(
      dynamic json, T Function(Object? json) fromJsonT) {
    if (json is String) {
      // 如果 json 是字符串类型，先解析为 Map<String, dynamic>
      json = jsonDecode(json);
    }
    return BaseResponse<T>(
      code: json['code'] as String?,
      response: json['response'] as String?,
      desc: json['desc'] as String?,
      data: json['data'] != null ? fromJsonT(json['data']) : null,
      message: json['message'] as String?,
    );
  }
}

class Page<T> {
  int? count; // 数据总量
  int? totalPages; // 总页数
  int? curPage; // 当前页码
  int? perPage; // 每页数量
  int? initNum; // 起始数
  List<T>? dtoList; // 泛型数据

  Page({
    this.count,
    this.totalPages,
    this.curPage,
    this.perPage,
    this.initNum,
    this.dtoList,
  });

  // fromJson 方法
  factory Page.fromJson(
    Map<String, dynamic> json,
    T Function(Map<String, dynamic>) fromJsonT,
  ) {
    return Page<T>(
      count: json['count'] as int?,
      totalPages: json['totalPages'] as int?,
      curPage: json['curPage'] as int?,
      perPage: json['perPage'] as int?,
      initNum: json['initNum'] as int?,
      dtoList: json['dtoList'] != null
          ? (json['dtoList'] as List).map((item) => fromJsonT(item)).toList()
          : null,
    );
  }
}
